/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package grace

import (
	"os"
	"os/signal"
	"sync"
	"errors"
	"syscall"
	"gitee.com/tugoer/orivil/log"
)

var once = sync.Once{}

func ListenSignal(onShutdown func() error) (closed <-chan struct{}) {
	once.Do(func() {
		idleConnsClosed := make(chan struct{})
		go func() {
			sigint := make(chan os.Signal, 1)
			signal.Notify(sigint, os.Interrupt, os.Kill, syscall.SIGTERM)
			<-sigint
			log.Info.Println("Shutting down...")
			if err := onShutdown(); err != nil {
				log.Warning.Printf("Shutdown: %v\n", err)
			}
			idleConnsClosed <- struct{}{}
		}()
		closed = idleConnsClosed
	})
	if closed == nil {
		panic(errors.New("already listened signal"))
	}
	return
}